<template>
  <div class="sale-team">
    <ul class="tab-list">
      <li class="tab" @click="changeType(0)">
        <div class="content" :class="{active: type === 0}">
          <img class="icon" src="/static/images/index/icon.png">个人日销售排名
        </div>
      </li>
      <li class="tab"  @click="changeType(1)">
        <div class="content" :class="{active: type === 1}">
          <img class="icon" src="/static/images/index/icon.png">个人月销售排名
        </div>
      </li>
    </ul>
    <div class="data-content">
      <div class="canvas">
        <div class="unit">单位(元)</div>
        <m-echarts :echarts="echarts" :onInit="initChart" ref="chart" canvasId="salePerson"/>
      </div>
      <div class="table" v-show="type === 0">
        <div class="tr">
          <div class="th" style="width: 120rpx;">姓名</div>
          <div class="th" style="width: 170rpx;">团队</div>
          <div class="th" style="width: 100rpx;">成单单数</div>
          <div class="th" style="width: 120rpx;">成单金额</div>
          <div class="th" style="width: 100rpx;">新购金额</div>
          <div class="th" style="width: 100rpx;">复购金额</div>
        </div>
        <div class="tr" v-for="(data,index) in dayData" :key="index">
          <div class="td" style="width: 120rpx;">{{data.salesName}}</div>
          <div class="td" style="width: 170rpx;">{{data.orgName}}</div>
          <div class="td" style="width: 100rpx;">{{data.totalOrderNum}}</div>
          <div class="td" style="width: 120rpx;">{{data.totalOrderAmount}}</div>
          <div class="td" style="width: 100rpx;">{{data.newOrderAmount}}</div>
          <div class="td" style="width: 100rpx;">{{data.rebuyOrderAmount}}</div>
        </div>
      </div>
      <div class="table" v-show="type === 1">
        <div class="tr">
          <div class="th" style="width: 120rpx;">姓名</div>
          <div class="th" style="width: 170rpx;">团队</div>
          <div class="th" style="width: 100rpx;">成单单数</div>
          <div class="th" style="width: 120rpx;">成单金额</div>
          <div class="th" style="width: 100rpx;">广告费</div>
          <div class="td" style="width: 100rpx;">ROI</div>
        </div>
        <div class="tr" v-for="(data,index) in monthData" :key="index">
          <div class="td" style="width: 120rpx;">{{data.salesName}}</div>
          <div class="td" style="width: 170rpx;">{{data.orgName}}</div>
          <div class="td" style="width: 100rpx;">{{data.totalOrderNum}}</div>
          <div class="td" style="width: 120rpx;">{{data.totalOrderAmount}}</div>
          <div class="td" style="width: 100rpx;">{{data.adCost}}</div>
          <div class="td" style="width: 100rpx;">{{data.roi}}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import * as echarts from "utils/echarts";
  import mEcharts from "components/echarts";
  import timeFormat from "utils/time-format";
  import _ from 'lodash';

  export default {
    data() {
      return {
        echarts,
        type: 0,
        dayData: [],
        monthData: [],
        monthOption: {},
        dayOption: {},
      };
    },
    components: {
      mEcharts
    },
    methods: {
      async changeType(type) {
        this.type = type;
        if(this.type === 1 && !this.monthData.length){
          await this.loadMonth();
        }
        this.chart.setOption(type === 1 ? this.monthOption : this.dayOption);
      },
      initChart(canvas, width, height) {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(chart);
        this.chart = chart;
        return chart;
      },
      async loadMonth(){
        wx.showLoading();
        const result = await wx.request({
          url: "/bg/sales/report/salesRankReport",
          data: {
            startTime: timeFormat.fetch(Date.now(), "{YYYY}-{MM}-01 00:00:00"),
            endTime: timeFormat.fetch(Date.now(), "{YYYY}-{MM}-31 23:59:59")
          }
        });
        wx.hideLoading()
        if (result.code === 200) {
          let list = [], orgList = [], saleList = [];
          const countColumn = ['totalOrderNum', 'totalOrderAmount', 'adCost'];
          const totalData = {
            salesName: '合计',
            orgName: '合计',
          }
          countColumn.forEach(column => {
            totalData[column] = 0;
          })
          result.data.forEach(data => {
            if(App.isLeader && data.orgId !== App.orgId){
              return false;
            }
            const pickData = _.pick(data, ['salesName', 'orgName', 'totalOrderNum', 'totalOrderAmount', 'adCost'])
            pickData.totalOrderAmount = isNaN(pickData.totalOrderAmount) ? 0 : parseInt(pickData.totalOrderAmount || 0);
            pickData.adCost = isNaN(pickData.adCost) ? 0 : parseInt(pickData.adCost || 0);
            pickData.roi = pickData.adCost ? parseFloat(pickData.totalOrderAmount / pickData.adCost).toFixed(2) : pickData.totalOrderAmount;
            if(orgList.length < 15){
              orgList.push(pickData.salesName);
              saleList.push(pickData.totalOrderAmount);
            }
            countColumn.forEach(column => {
              totalData[column] += pickData[column];
            })
            list.push(pickData);
          });
          totalData.roi =  totalData.adCost ? parseFloat(totalData.totalOrderAmount / totalData.adCost).toFixed(2) : totalData.totalOrderAmount;
          list.push(totalData)
          this.monthData = list;
          this.monthOption = {
            color: [ new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                {offset: 0, color: '#4048EF'},
                {offset: 1, color: '#5A7BEF'}
              ]
            ) ],
            grid: {
              left: "0%",
              right: "0%",
              bottom: "0%",
              top: "2%",
              containLabel: true
            },
            xAxis: [
              {
                type: "category",
                data: orgList,
                axisLabel:{
                  interval:0,
                  rotate:45,
                  margin: 10,
                  textStyle:{
                    color:"#707070"
                  }
                },
                axisTick: {
                  alignWithLabel: true
                }
              }
            ],
            yAxis: [
              {
                type: "value"
              }
            ],
            series: [
              {
                name: "销售额",
                type: "bar",
                barWidth: "50%",
                data: saleList
              }
            ]
          };
        } else {
          wx.showToast(result.message);
        }
      },
      async init() {
        wx.showLoading();
        const result = await wx.request({
          url: "/bg/sales/report/salesRankReport",
          data: {
            startTime: timeFormat.fetch(Date.now(), "{YYYY}-{MM}-{DD} 00:00:00"),
            endTime: timeFormat.fetch(Date.now(), "{YYYY}-{MM}-{DD} 23:59:59")
          }
        });
        wx.hideLoading();
        if (result.code === 200) {
          let list = [], orgList = [], saleList = [];
          const countColumn = ['totalOrderNum', 'totalOrderAmount', 'newOrderAmount', 'rebuyOrderAmount', 'adCost']
          const totalData = {
            salesName: '合计',
            orgName: '合计',
          }
          countColumn.forEach(column => {
            totalData[column] = 0;
          })
          result.data.forEach(data => {
            if(App.isLeader && data.orgId !== App.orgId){
              return false;
            }
            const pickData = _.pick(data, ['salesName', 'orgName', 'totalOrderNum', 'totalOrderAmount', 'newOrderAmount', 'rebuyOrderAmount', 'adCost'])
            pickData.totalOrderAmount = isNaN(pickData.totalOrderAmount) ? 0 : parseInt(pickData.totalOrderAmount || 0);
            pickData.newOrderAmount = isNaN(pickData.newOrderAmount) ? 0 : parseInt(pickData.newOrderAmount || 0);
            pickData.rebuyOrderAmount = isNaN(pickData.rebuyOrderAmount) ? 0 : parseInt(pickData.rebuyOrderAmount || 0);
            pickData.adCost = isNaN(pickData.adCost) ? 0 : parseInt(pickData.adCost || 0);
            pickData.roi = pickData.adCost ? parseFloat(pickData.totalOrderAmount / pickData.adCost).toFixed(2) : pickData.totalOrderAmount;
            if(orgList.length < 15){
              orgList.push(pickData.salesName);
              saleList.push(pickData.totalOrderAmount);
            }
            countColumn.forEach(column => {
              totalData[column] += pickData[column];
            })
            list.push(pickData);
          });
          list.push(totalData)
          this.dayData = list;
          this.dayOption = {
            color: [new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                {offset: 0, color: '#4048EF'},
                {offset: 1, color: '#5A7BEF'}
              ]
            ) ],
            grid: {
              left: "0%",
              right: "0%",
              bottom: "0%",
              top: "2%",
              containLabel: true
            },
            xAxis: [
              {
                type: "category",
                axisLabel:{
                  interval:0,
                  rotate:45,
                  margin: 10,
                  textStyle:{
                    color:"#707070"
                  }
                },
                data: orgList,
                axisTick: {
                  alignWithLabel: true
                }
              }
            ],
            yAxis: [
              {
                type: "value"
              }
            ],
            series: [
              {
                name: "销售额",
                type: "bar",
                barWidth: "50%",
                data: saleList
              }
            ]
          };
          this.chart.setOption(this.dayOption);
        } else {
          wx.showToast(result.message);
        }
      }
    }
  };
</script>

<style lang="scss">
  @import "../../../styles/base";

  .sale-team {
    padding-top: pxToRem(20);
    .tab-list {
      display: flex;
      align-items: center;
      padding-bottom: pxToRem(5);
      border-bottom: pxToRem(1) solid #F5F5F5;
      .tab {
        position: relative;
        flex: 1;
        &:first-child {
          border-right: pxToRem(1) solid #F5F5F5;
        }
        .content {
          position: relative;
          display: flex;
          align-items: center;
          flex-wrap: nowrap;
          width: pxToRem(255);
          margin-left: auto;
          margin-right: auto;
          padding-top: pxToRem(14);
          padding-bottom: pxToRem(10);
          .icon {
            opacity: 0;
            margin-right: pxToRem(10);
            width: pxToRem(16);
            height: pxToRem(26);
          }
          line-height: pxToRem(44);
          font-size: pxToRem(32);
          color: #707070;
          &.active {
            .icon {
              opacity: 1;
            }
            color: #44BDF5;
            &:after {
              content: '';
              position: absolute;
              left: 0;
              right: 0;
              bottom: pxToRem(-6);
              height: pxToRem(6);
              background: linear-gradient(90deg, rgba(117, 228, 252, 1) 0%, rgba(68, 189, 245, 1) 100%)
            }
          }
        }
      }
    }
    .data-content {
      padding: pxToRem(20);
      box-sizing: border-box;
      .canvas {
        position: relative;
        margin: pxToRem(90) auto pxToRem(40);
        width: pxToRem(710);
        height: pxToRem(500);
        .unit {
          position: absolute;
          right: 0;
          top: pxToRem(-50);
          font-size: pxToRem(24);
          color: #707070;
        }
      }
    }
  }
</style>
